import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

interface UserInfo {
  id: string
  username: string
  nickname: string
  avatar: string
  token: string
  phone?: string
  email?: string
}

export const useUserStore = defineStore('user', () => {
  // state
  const userInfo = ref<UserInfo | null>(null)
  
  // getters
  const isLogin = computed(() => !!userInfo.value?.token)
  const userId = computed(() => userInfo.value?.id || '')
  const nickname = computed(() => userInfo.value?.nickname || '未登录')
  
  // actions
  const setUserInfo = (info: UserInfo) => {
    userInfo.value = info
    // 持久化存储
    uni.setStorageSync('userInfo', JSON.stringify(info))
  }
  
  const updateUserInfo = (info: Partial<UserInfo>) => {
    if (userInfo.value) {
      userInfo.value = { ...userInfo.value, ...info }
      uni.setStorageSync('userInfo', JSON.stringify(userInfo.value))
    }
  }
  
  const clearUserInfo = () => {
    userInfo.value = null
    uni.removeStorageSync('userInfo')
  }
  
  const initUserInfo = () => {
    try {
      const data = uni.getStorageSync('userInfo')
      if (data) {
        userInfo.value = JSON.parse(data)
      }
    } catch (e) {
      console.error('初始化用户信息失败', e)
    }
  }
  
  // 模拟登录
  const login = async (params: { username: string; password: string }) => {
    // 这里应该调用真实的登录API
    return new Promise<UserInfo>((resolve) => {
      setTimeout(() => {
        const mockUser: UserInfo = {
          id: '1001',
          username: params.username,
          nickname: '测试用户',
          avatar: '/static/logo.png',
          token: 'mock-token-' + Date.now(),
          phone: '13800138000'
        }
        setUserInfo(mockUser)
        resolve(mockUser)
      }, 1000)
    })
  }
  
  // 退出登录
  const logout = () => {
    clearUserInfo()
    // 跳转到首页
    uni.reLaunch({
      url: '/pages/index/index'
    })
  }
  
  return {
    // state
    userInfo,
    // getters
    isLogin,
    userId,
    nickname,
    // actions
    setUserInfo,
    updateUserInfo,
    clearUserInfo,
    initUserInfo,
    login,
    logout
  }
}) 